﻿//命名空间
var MYAPP = MYAPP || {};
MYAPP.namespace = function (ns_string) {
    var parts = ns_string.split('.'),
          parent = MYAPP,
          i;

    if (parts[0] === "MYAPP") {
        parts = parts.slice(1);
    }

    for (i = 0, len = parts.length; i < len; i++) {
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

var module2 = MYAPP.namespace('MYAPP.modules.module2');
console.log(module2 === MYAPP.modules.module2);

//定义依赖
var myFunction = function () {
    //依赖模块
    var event = YAHOO.until.Event,
          dom = YAHOO.until.dom;

    //其他函数
};

//私有属性和私有方法
function Gadget() {
    var name = "iPod";
    this.getName = function () {
        return name;
    };
}

var toy = new Gadget();
console.log(toy.name);
console.log(toy.getName());

var myobj;
(function () {
    var name = "my ,oh my";
    myobj = {
        getName: function () {
            return name;
        }
    };
}());

//Revelation模式
var myarry;
(function () {
    var astr = "[object Array]",
          toString = object.prototype.toString;

    function isArray(a) {
        return tostring.call(a) === astr;
    }

    function indexOf(haystack, needle) {
        var i = 0,
              max = haystack.length;
        for (; i < max; i++) {
            if (haystack[i] === needle) {
                return i;
            }
        }
        return -1;
    }

    myarry = {
        isArray: isArray,
        indexOf: indexOf,
        inArray: indexOf
    };
}());

console.log(myarry.isArray([1, 2]));
console.log(myarry.inArray({ 0: 1 }));
console.log(myarry.indexOf(["a", "b", "z"], "z"));
console.log(myarry.inArray(["a", "b", "z"], "z"));
myarry.indexOf = null;
console.log(myarry.inArray(["a", "b", "z"], "z"));

//链模式
var obj = {
    value: 1,
    increment: function () {
        this.value += 1;
        return this;
    },
    add: function (v) {
        this.value += v;
        return this;
    },
    shout: function () {
        console.log(this.value);
    }
};
//调用方法
obj.increment().add(1).shout();